package com.tt.dp.component;

import java.util.Iterator;
import java.util.Stack;

public class CompositeIterator implements Iterator<MenuComponent> {

    private Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>();

    public CompositeIterator(Iterator<MenuComponent> iterator) {
        stack.push(iterator);
    }

    public boolean hasNext() {

        if(stack.empty()){
            return false;
        }else{
            Iterator it = stack.peek();

            if(!it.hasNext()){
                stack.pop();
                return hasNext();
            }else{
                return true;
            }
        }
    }

    public MenuComponent next() {

        if(hasNext()){
            Iterator<MenuComponent> it = stack.peek();

            MenuComponent item = it.next();

            if(item instanceof Menu){
                stack.push(item.createIterator());
            }

            return item;
        }else{
            return null;
        }
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}
